﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebUI.Areas.Bots.Models;
using Entities;
using WebUI.Models;
using Services;
using DAL;

namespace WebUI.Areas.Bots.Controllers
{
    public partial class OperationsController : BaseController
    {
        #region Member Variables

        readonly IBotService _botService;
        readonly IOperationRepository _operationRepository;

        #endregion

        #region Constructor

        public OperationsController(ISessionHelper sessionHelper, IBotService botService, IOperationRepository operationRepository)
            : base(sessionHelper)
        {
            this._botService = botService;
            this._operationRepository = operationRepository;
        }

        #endregion

        #region Action Methods

        public virtual ViewResult Index()
        {
            var allOperations = _operationRepository.GetAll();
            var selectedOperations = _sessionHelper.Bot.BotsOperations.Select(o => o.OperationId);
            
            var Operation = new Operations
            {
                IsAllOperations = _sessionHelper.Bot.AllOps,
                SelectedOperations = allOperations.Where(e => selectedOperations.Contains(e.OperationID)),
                AllOperations = allOperations,
            };

            return View(Operation);
        }

        [HttpPost]
        public virtual ActionResult Save(Operations model, IEnumerable<string> selectedOperations)
        {
            if (selectedOperations != null)
            {
                _sessionHelper.Bot.BotsOperations = new TrackableCollection<BotsOperation>();

                foreach (var operation in selectedOperations)
                {
                    _sessionHelper.Bot.BotsOperations.Add(new BotsOperation { OperationId = short.Parse(operation) });
                }
            }

            _sessionHelper.Bot.AllOps = model.IsAllOperations;
            IDictionary<string, string> validationDictionary = _botService.ValidateBotOperationsStep(selectedOperations, model.IsAllOperations);

            foreach (var entry in validationDictionary.Values)
            {
                ModelState.AddModelError(string.Empty, entry);
            }

            if (validationDictionary.Count == 0)
            {
                return RedirectToRoute(new { action = "Index", controller = MVC.Bots.UsersAndMachines.Name, step = MVC.Bots.UsersAndMachines.Name });
            }

            model.AllOperations = _operationRepository.GetAll();

            return View(MVC.Bots.Operations.Views.Index, model);
        }

        #endregion
    }
}